//
//  RecruitmentInfo.m
//  HappyStore
//
//  Created by 李小辉 on 16/6/14.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "RecruitmentInfo.h"
#import "RecruitmentView.h"
#import "UsedTool.h"
#import "EditBiography.h"
#import "goveDetailVC.h"
#import "thirdPersonVC.h"
@interface RecruitmentInfo ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *submitResumeBtn;//投递简历
@property (strong, nonatomic) RecruitmentView *recruView;//视图
@property (assign, nonatomic) CGFloat numWebViewHeight;
@property (assign, nonatomic) NSInteger numHeight;//记录点击（展开/收起）的次数
@property (strong, nonatomic) NSDictionary *dicData; //数据源
@property (strong, nonatomic) NSString *isResume;//判断是否已投递简历
@property (strong, nonatomic) UIButton *rightBtn; //关注按钮
@property (strong, nonatomic) NSString *isfocus; //判断是否关注
@end

@implementation RecruitmentInfo


//初始化
- (RecruitmentView *)recruView{
    if (!_recruView) {
        _recruView = [[[NSBundle mainBundle] loadNibNamed:@"RecruitmentView" owner:self options:nil] lastObject];
    }
    return _recruView;
}

-(NSDictionary *)dicData{
    if (!_dicData) {
        _dicData = [NSDictionary dictionary];
    }
    return _dicData;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = NO;
    navBarHairlineImageView.alpha = 0.5f;
    //开始任务
    [self startNetWork];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = YES;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"职位详情";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    
    //收藏按钮
    self.rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [self.rightBtn addTarget:self action:@selector(clickRightBarEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    //取消返回的文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    [self.recruView.clickBtn addTarget:self action:@selector(clickButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    //判断是否是个人，个人才有投递简历
    if ([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 1) {
        self.submitResumeBtn.hidden = NO;
    }else{
        self.submitResumeBtn.hidden = YES;
    }
    //投递简历
    [self.submitResumeBtn addTarget:self action:@selector(submitResume) forControlEvents:UIControlEventTouchUpInside];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    
    self.numHeight = 1;
    
}


////设置上半view
-(void)setupRecruitmentView{


    self.recruView.titleLabel.text = self.dicData[@"positionName"];

    //薪资
    self.recruView.moneyLabel.text = [UsedTool moneyChange:self.dicData[@"money"]];
    //地址
    if ([self.dicData[@"address"] isEqualToString:@"null"]||self.dicData[@"address"] == nil) {
        self.recruView.cityShiLabel.text = @" ";
    }else{
        NSArray *addressAry = [self.dicData[@"address"] componentsSeparatedByString:@"-"];
        if (addressAry[0]) {
            self.recruView.cityShiLabel.text = addressAry[0];
        }
//        NSArray *addressAry = [self.dicData[@"address"] componentsSeparatedByString:@"/"];
//        if ([addressAry lastObject]) {
//            NSString *addStr = [self.dicData[@"address"] substringWithRange:NSMakeRange(0, [self.dicData[@"address"] length]-1)];
//            self.recruView.cityShiLabel.text = addStr;
//            
//        }else{
//            self.recruView.cityShiLabel.text = self.dicData[@"address"];
//        }
    }
    self.recruView.addressCompanyLabel.text = self.dicData[@"recruitCompany"];
    [self.recruView.headPhoto sd_setImageWithURL:[NSURL URLWithString:self.dicData[@"headPhoto"]] placeholderImage:[UIImage imageNamed:@"20100403114758394_4147"]];
    
    
    //个人的职位
    self.recruView.nameLabel.text = self.dicData[@"username"];
    if (self.dicData[@"username"]==nil||[self.dicData[@"username"] isEqualToString:@""]||[self.dicData[@"username"] isEqualToString:@"null"]) {
        self.recruView.nameLabel.text = self.dicData[@"account"];
    }
    
    if ([self.dicData[@"userType"] integerValue]==1) {
        self.recruView.poinLabel.text = self.dicData[@"posiTionName"];
        if (self.dicData[@"posiTionName"]==nil||[self.dicData[@"posiTionName"] isEqualToString:@"null"]) {
            self.recruView.poinLabel.text =@"";
        }
    }else{
        self.recruView.xiaoView.backgroundColor = [UIColor whiteColor];
    }
    
    
//    if ([self.dicData[@"authState"] integerValue]==2) {
//        self.recruView.authImageView.image = [UIImage imageNamed:@"yirenzheng"];
//    }else{
//        self.recruView.authImageView.image = [UIImage imageNamed:@"weirenzheng"];
//    }
    //认证
    self.recruView.isAuthState.hidden = [UsedTool authStateImageViewHidden:self.dicData[@"authState"]];
    //会员图标
    self.recruView.authImageView.image = [UsedTool setVipimage:self.dicData[@"vipLevel"]];
    //判断上级
    self.recruView.companyLabel.text = [UsedTool userType:self.dicData[@"userType"] companyName:self.dicData[@"companyName"] userAddress:self.dicData[@"userAddress"]];
    
    
    [self.recruView.jumpBtn addTarget:self action:@selector(goGoveBy) forControlEvents:UIControlEventTouchUpInside];
    
    //设置工龄、学位、等标签
    //工龄

    
    self.recruView.experienceLabel.text = self.dicData[@"experience"];
    self.recruView.experienceLabel.layer.borderColor = RGB(23, 176, 216).CGColor;
    //学历

    self.recruView.educationLabel.text = self.dicData[@"schooling"];
    
    //设置边框颜色
    self.recruView.educationLabel.layer.borderColor = RGB(23, 176, 216).CGColor;
    //职位描述 － webview
    self.recruView.descriptionWebView.delegate = self;
    NSURL *url = [NSURL URLWithString:self.dicData[@"description"]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //加载webview
    [self.recruView.descriptionWebView loadRequest:request];
    
    self.recruView.descriptionWebView.scrollView.bounces = NO;
    self.recruView.descriptionWebView.scrollView.scrollEnabled = NO;
    self.recruView.descriptionWebView.hidden = YES;
    self.recruView.descriptionWebView.scrollView.contentInset = UIEdgeInsetsMake(-50, 0, 0, 0);
    self.recruView.frame = CGRectMake(0, 0, screenW, self.recruView.descriptionWebView.y+self.recruView.descriptionConstraint.constant +100);
  
    [self.scrollView addSubview:self.recruView];
   
    self.scrollView.contentSize = CGSizeMake(screenW, self.recruView.height +100);
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    self.numWebViewHeight = webView.scrollView.contentSize.height;
    //处理“下载app的广告”
    NSString *downloadHeaderJSStr = @"document.getElementById(\"top-app-layer\").style.visibility=\"hidden\"";
    [webView stringByEvaluatingJavaScriptFromString:downloadHeaderJSStr];
    [self performSelector:@selector(btnDismiss) withObject:nil afterDelay:0.4f];
    
}

- (void)btnDismiss{
    self.recruView.descriptionWebView.hidden = NO;
}

#pragma mark - 点击个人跳转
-(void)goGoveBy{
    if ([self.dicData[@"userType"] integerValue] == 3) {
        goveDetailVC * goveVC = [[goveDetailVC alloc]init];
        goveVC.userId = self.dicData[@"userId"];
        goveVC.userType = self.dicData[@"userType"];
        [self.navigationController pushViewController:goveVC animated:YES];
    }else{
        thirdPersonVC *thirdVC = [[thirdPersonVC alloc] init];
        thirdVC.userId = self.dicData[@"userId"];
        thirdVC.userType = self.dicData[@"userType"];
        [self.navigationController pushViewController:thirdVC animated:YES];
    }
    
    
}
#pragma mark - 收藏按钮
- (void)clickRightBarEvent{
    
    if ([USER_DEFAULTS objectForKey:@"userid"]!=nil) {
        
        //NSLog(@"self.isFocus:%@",self.isfocus);
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        dic[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
        dic[@"token"] = [USER_DEFAULTS objectForKey:@"token"];
        dic[@"resId"] = self.jobId;
        dic[@"resType"] = @(5);
        NSString *strURL = @"";
        if ([self.isfocus isEqualToString:@"否"]) {
            strURL = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"focusResources_app_action.im.lensum"];
            
        }else{
            strURL = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"focusResourcesCancel_app_action.im.lensum"];
        }
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:strURL parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            if ([dicInfo[@"result"] integerValue] == 1) {
                if ([self.isfocus isEqualToString:@"否"]) {
                    
                    [self.rightBtn setImage:[UIImage imageNamed:@"shouchanghuang"] forState:UIControlStateNormal];
                    
                    self.isfocus = @"是";
                }else{
                    [self.rightBtn setImage:[UIImage imageNamed:@"shouchang"] forState:UIControlStateNormal];
                    self.isfocus =@"否";
                }

            }
            if ([dicInfo[@"result"] integerValue] == 2) {
                if ([self.isfocus isEqualToString:@"否"] ) {
                    self.isfocus =@"否";
                }else{
                    self.isfocus = @"是";
                }

            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            [self showSingleIconBubble:@"网络连接错误"];

        }];
        
    
        
    }else{
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
}


#pragma mark - 点击投递简历
- (void)submitResume{
    EditBiography *editbiographyVC = [[EditBiography alloc] init];
    editbiographyVC.jobId = self.jobId;
    editbiographyVC.userid = self.dicData[@"userId"];
    [self.navigationController pushViewController:editbiographyVC animated:YES];


}



//展开收起事件
- (void)clickButtonEvent:(UIButton *)btn{
    
    btn.selected = !btn.selected;
 
    self.numHeight += 1;
    if (self.numHeight%2==0) {
        
        self.recruView.descriptionConstraint.constant = self.numWebViewHeight;
        
    }else{
        self.recruView.descriptionConstraint.constant = 100.0f;
        
    }
    [self setupRecruitmentView];
}







- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求
- (void)startNetWork{
    [self showRoundProgressWithTitle:@"请稍后..."];
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    
    muDicParameters[@"jobId"] = self.jobId;
    if ([USER_DEFAULTS objectForKey:@"userid"] != nil) {
        muDicParameters[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
    }
    
    NSString *strURL = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"jobhuntingDetail_app_jobhunting.im"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:strURL parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        if ([dicInfo[@"result"] integerValue] ==1) {
            self.dicData = dicInfo[@"data"];
            //是否关注
            self.isfocus = self.dicData[@"isfocus"];
            if ([self.isfocus isEqualToString:@"是"]) {
                [self.rightBtn setImage:[UIImage imageNamed:@"shouchanghuang"] forState:UIControlStateNormal];
            }else{
                [self.rightBtn setImage:[UIImage imageNamed:@"shouchang"] forState:UIControlStateNormal];
            }
            
            
            //是否已投递简历
            self.isResume = self.dicData[@"isResume"];
            if ([self.isResume isEqualToString:@"是"]) {
                [self.submitResumeBtn setTitle:@"已投递" forState:UIControlStateNormal];
                self.submitResumeBtn.enabled = NO;
            }else{
                [self.submitResumeBtn setTitle:@"投递简历" forState:UIControlStateNormal];
                self.submitResumeBtn.enabled = YES;
            }
            
            
        }
        
        //加载视图
        [self setupRecruitmentView];
        [self hideBubble];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self showSingleIconBubble:error.localizedDescription];

    }];
    
}








@end
